import { FieldCols, FormSection, mapField, useCall, useReq } from '@/components';
import request from '@/utils/request';
import { Form, message } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useMemo } from 'react';
import { usePackageData } from './PackageContext';

EditQuest = forwardRef(EditQuest);

function updateQuest(productCodes, questCode, options = null) {
  return request.post(
    '/product/updateQuestCode',
    productCodes.map((productCode) => ({
      productCode,
      questCode,
    })),
    options,
  );
}

function getQuestOptions(companyCode, options = null) {
  return request.post('../smart/policy/question/getQuestionInfoByCompanyCode', null, {
    ...options,
    params: { companyCode },
  });
}

/**
 * 配置主险的问卷code
 * questCode: "{\"holderQuest\":[],\"insuredQuest\":[\"N118\",\"N123\",\"N124\"],\"agentQuest\":[]}"
 */
function EditQuest(props, ref) {
  const packageData = usePackageData();
  const update = useReq(updateQuest);
  const getOptions = useReq(getQuestOptions);

  // 从package获取回显值
  const [questCode, mainProdCodes, companyCode] = useMemo(() => {
    // 问卷code回显
    let questCode = packageData?.plans[0].requestProducts[0].questCode;
    try {
      questCode = JSON.parse(questCode);
    } catch {}

    // 各计划的主险code
    let mainProdCodes = packageData?.plans.map((v) => v.requestProducts[0].businessCode) || [];

    // 保险公司code
    let companyCode = packageData?.companyCode;

    return [questCode, mainProdCodes, companyCode];
  }, [packageData]);

  const onSave = useCall(async () => {
    let questCode = form.getFieldsValue();

    const codes = ['holderQuest', 'insuredQuest', 'agentQuest'];
    const questCodeSize = Math.max(...codes.map((k) => questCode[k]?.length));

    if (!questCodeSize) {
      message.error('请选择问卷配置');
      throw '请选择问卷配置';
    }
    questCode = JSON.stringify(questCode);

    return update.start(mainProdCodes, questCode);
  });
  useImperativeHandle(ref, () => ({ onSave }));

  // 用companyCode获取问卷的下拉选项
  const options = getOptions.result?.data.questionaireList.map(mapOption) || [];

  function mapOption(item) {
    return {
      value: item.qustionairecode,
      // label: `${item.qname} (${item.qustionairename})`,
      label: `${item.qname} (${item.qustionairecode})`,
    };
  }

  useEffect(() => {
    if (companyCode) getOptions.start(companyCode);
    return getOptions.cancel;
  }, [companyCode]);

  // 定义表单
  const [form] = Form.useForm();
  useEffect(() => {
    form.resetFields();
    if (questCode) form.setFieldsValue(questCode);
  }, [questCode]);

  const fields = [
    ['holderQuest', '投保人问卷', 'select', { initialValue: [], mode: 'multiple', options }],
    ['insuredQuest', '被保人问卷', 'select', { initialValue: [], mode: 'multiple', options }],
    ['agentQuest', '经纪人问卷', 'select', { initialValue: [], mode: 'multiple', options }],
  ].map(mapField);

  return (
    <Form form={form} component={false}>
      <FormSection title='问卷配置'>
        <FieldCols form={form} fields={fields} />
      </FormSection>
    </Form>
  );
}

export default EditQuest;
